package com.wangxiaonan.coupon.controller;

import com.wangxiaonan.coupon.common.ResponseWrapper;
import com.wangxiaonan.coupon.domain.CouponInfo;
import com.wangxiaonan.coupon.domain.CouponIssue;
import com.wangxiaonan.coupon.domain.dto.CouponInfoDto;
import com.wangxiaonan.coupon.domain.dto.CouponIssueDto;
import com.wangxiaonan.coupon.service.CouponInfoService;
import com.wangxiaonan.coupon.service.CouponIssueService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.annotation.Resource;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: wangxiaonan
 * @Date: 2019/1/10
 **/
@RestController
@RequestMapping("coupon")
@Api(value = "coupon", description = "coupon")
public class CouponController {

    @Resource
    private CouponInfoService couponInfoService;
    @Resource
    private CouponIssueService couponIssueService;

    @ApiOperation(value = "创建优惠券", httpMethod = "PUT")
    @RequestMapping(method = RequestMethod.PUT)
    public ResponseWrapper createCoupon(@RequestBody CouponInfoDto couponInfo) {
        Assert.notNull(couponInfo.getCirculation(), "发行量不能为空");
        CouponInfo info = new CouponInfo();
        info.setCirculation(couponInfo.getCirculation());
        info.setCouponName(couponInfo.getCouponName());
        info.setLimit(couponInfo.getLimit());
        info.setStatus(couponInfo.getStatus());
        info.setExpireDate(couponInfo.getExpireDate());
        info = couponInfoService.save(info);
        return new ResponseWrapper().success().addData(info);
    }

    @ApiOperation(value = "发布优惠券", httpMethod = "POST")
    @RequestMapping(value = "/{id}", method = RequestMethod.POST)
    public ResponseWrapper publish(@PathVariable(name = "id") Integer couponId) {
        CouponInfo info = couponInfoService.findById(couponId);
        Assert.notNull(info, "优惠券不存在");
        boolean isSuccess = couponInfoService.publish(info);
        return new ResponseWrapper().success().addData(isSuccess);
    }

    @ApiOperation(value = "优惠券领取", httpMethod = "POST")
    @RequestMapping(value = "/receive", method = RequestMethod.POST)
    public ResponseWrapper receive(@RequestBody CouponIssueDto coupon) {
        CouponInfo info = couponInfoService.findById(coupon.getCouponId());
        Assert.notNull(info, "优惠券不存在");
        CouponIssue issue = couponIssueService.receive(coupon.getUserName(), info);
        return new ResponseWrapper().success().addData(issue.getIssueNum());
    }

}
